﻿using System.Net.Sockets; 
using System.Text; 

class LicenseClient
{
    private static string licenseKey;
    private static Timer heartbeatTimer;

    static void Main(string[] args)
    {
        Console.WriteLine("请输入许可证号：");
        licenseKey = Console.ReadLine(); 

        // 验证许可证
        string validateRequest = $"VALIDATE:{licenseKey}";
        string validateResponse = SendRequest(validateRequest);
        Console.WriteLine($"服务器响应：{validateResponse}");
        
        if (validateResponse.Contains("验证成功"))
        {
            heartbeatTimer = new Timer(SendHeartbeat, null, 0, 30000); // 启动定时发送回报
        }
        else
        {
            Console.WriteLine("许可证验证失败，无法启动软件。");
        }
        
        Console.WriteLine("按任意键退出...");
        Console.ReadKey();
        heartbeatTimer?.Dispose(); 
    }

    // 向服务器发送心跳消息
    private static void SendHeartbeat(object state)
    {
        string heartbeatRequest = $"HEARTBEAT:{licenseKey}";
        string heartbeatResponse = SendRequest(heartbeatRequest);
        Console.WriteLine($"心跳响应：{heartbeatResponse}");
    }

    // 向服务器发送请求的函数
    private static string SendRequest(string request)
    {
        try
        {
            using (var client = new TcpClient("127.0.0.1", 8080)) // 连接服务器
            {
                NetworkStream stream = client.GetStream();
                byte[] requestData = Encoding.UTF8.GetBytes(request);
                stream.Write(requestData, 0, requestData.Length);

                byte[] responseData = new byte[256];
                int bytesRead = stream.Read(responseData, 0, responseData.Length);
                return Encoding.UTF8.GetString(responseData, 0, bytesRead);
            }
        }
        catch (Exception ex)
        {
            return $"请求失败：{ex.Message}";
        }
    }
}